package elitech.vietnam.weatherfashion.backgroundtask;

import java.io.IOException;

import android.content.Context;
import android.os.AsyncTask;
import elitech.vietnam.weatherfashion.SplashScreenActivity;
import elitech.vietnam.weatherfashion.WFApplication;
import elitech.vietnam.weatherfashion.config.Const;
import elitech.vietnam.weatherfashion.config.GlobalValue;
import elitech.vietnam.weatherfashion.config.Utils;
import elitech.vietnam.weatherfashion.dto.MemberDTO;
import elitech.vietnam.weatherfashion.service.PHPSoapServiceCaller;
import elitech.vietnam.weatherfashion.ultilities.ValueOption;

public class SplashScreenTask extends AsyncTask<String, String, Boolean> {

	private SplashScreenActivity activity;

	public SplashScreenTask(SplashScreenActivity activity) {
		this.activity = activity;
	}

	@Override
	protected Boolean doInBackground(String... params) {

		// AUTO LOGIN
		ValueOption option = GlobalValue.getInstance(activity).readOptionInfo();
		if (option.isAutoLogin() && !option.getUsername().equals("")
				&& !option.getPassword().equals("")) {

			boolean b = false;
			PHPSoapServiceCaller appService = new PHPSoapServiceCaller();
			String gcmId = activity.getSharedPreferences(SplashScreenActivity.MAIN_PREF, Context.MODE_PRIVATE)
					.getString(SplashScreenActivity.PROPERTY_REG_ID, "");
			Utils.Log("Get User Info");
			try {
				MemberDTO user = appService.logIn(option.getUsername(),
						option.getPassword(), Const.COUNTRY_CODE);

				b = (user != null && user.getMemberArea().equals(
						Const.COUNTRY_CODE) && appService.setGCMID(user.getId(), gcmId));
				if (b == false) {
					user = null;					
				} else
					user.setGcmId(gcmId);
				GlobalValue.getInstance(activity).writeUserInfo(user);
			} catch (IOException e) {
				b = false;
			}

			Utils.Log("Get User Friend List");
			if (b) {
				try {
					MemberDTO user = GlobalValue.getInstance(activity)
							.readUserInfo();

					WFApplication.getInstance().userFriends = appService
							.getListFriend(user.getId());
					b = (WFApplication.getInstance().userFriends != null);
				} catch (IOException e) {
					b = false;
				}
			}
			if (!b)
				return false;
		} else {
			GlobalValue.getInstance(activity).writeUserInfo(null);
		}

		return null;
	}

	@Override
	protected void onPreExecute() {
		super.onPreExecute();
	}

	@Override
	protected void onPostExecute(Boolean result) {
		activity.finishLoading();
		activity = null;
	}
}
